//
//  RCTicketBookingVC.m
//  RocketProject
//
//  Created by chen jiedan on 13-9-3.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCTicketBookingVC.h"
#import "RCBookingHeaderSectionView.h"
#import "RCDepartureAndArriveView.h"
#import "RCAirFlyListVC.h"
#import "RCTrainListVC.h"
#import "CommonDefines.h"
#import "RCTopListTypeDataModel.h"
#import "RCToplistTypeView.h"
#import "UIColor-Expanded.h"
#import "RCEditAllCityVC.h"
#import "TravelException.h"
#import "NSArray+EX.h"
#import "CalendarVC.h"
#import "GloableEngineService.h"


@interface RCTicketBookingVC ()<RCBookingSectionViewProtocol,RCToplistTypeViewDelegate,RCDepartureAndArriveViewClickProtocol,RCEditCityProtocol,UIPickerViewDataSource,UIPickerViewDelegate,CalendarProtocol>{
    NSString  *_orderType;
    
    NSInteger  _rowNumberClick;
    NSInteger  _side;
    
    
    //火车类型
    NSArray *trainType;
    //火车类型 对应的座席类型
    NSArray *allTrainSeatType;
    NSArray *gaotieTrainSeatType;
    NSArray *putongTrainSeatType;
    
    NSArray *planeSeatType;

}
@property(nonatomic,retain) UIButton *headerTitleButton;
@property(nonatomic,retain) UILabel *headerTitleLabel;
@property (nonatomic, retain) NSString *orderType;
@property(nonatomic,retain) RCToplistTypeView *typeListView;
@property(nonatomic,retain) UIButton *transparentButton;

@end

@implementation RCTicketBookingVC{
    TicketType      _type;
    RCDepartureAndArriveView *_departureView;
    RCDepartureAndArriveView *_timeView;
    RCDepartureAndArriveView *_seatTypeView;
    
    UIView         *trainToolBar;
    UIPickerView   *_trainPickerView;
    UIView         *planeToolBar;
    UIPickerView   *_planePickerView;
}
@synthesize headerTitleButton = _headerTitleButton;
@synthesize headerTitleLabel = _headerTitleLabel;
@synthesize orderType = _orderType;
@synthesize typeListView = _typeListView;
@synthesize transparentButton = _transparentButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (id) initWithType:(TicketType)trafficType
{
    self = [super init];
    if (self) {
        _type = trafficType;
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
   
//    self.navigationItem.titleView = [self createTitleView];
    trainType = [[NSArray alloc] initWithObjects:@"全部",@"高铁动车",@"普通车", nil];
    allTrainSeatType = [[NSArray alloc] initWithObjects:@"不限",@"一等座",@"二等座",@"软卧",@"硬座",@"软座",@"硬卧", nil];
    gaotieTrainSeatType = [[NSArray alloc] initWithObjects:@"不限",@"一等座",@"二等座",@"软卧", nil];
    putongTrainSeatType = [[NSArray alloc] initWithObjects:@"不限",@"硬座",@"软座",@"硬卧",@"软卧", nil];
    
    planeSeatType = [[NSArray alloc] initWithObjects:@"经济舱",@"公务/头等舱", nil];


    
    [self createTitleButtonView];
    
  
    [self setViewContainerSubviews];
  
}


- (void) setViewContainerSubviews
{
    NSArray *subViews = self.viewContainer.subviews;
    for (UIView *subView in subViews) {
        [subView removeFromSuperview];
    }
    
    
    CGFloat diffHeight = 45;

    /*
    CGFloat diffHeight = 0;
    
    
    
    if (_type == TicketType_Air) {
        //        self.titleLabelText = @"国内/国际机票";
    }else{
        //        self.titleLabelText = @"火车票";
        diffHeight = 45;
    }
    
    if (_type == TicketType_Air) {
        RCBookingHeaderSectionView *sectionHeader = [[RCBookingHeaderSectionView alloc] initWithFrame:CGRectMake(72, 17, 320-72*2, 35) andTitlesArray:[NSArray arrayWithObjects:@"TEST1",@"TEST2", nil]];
        [self.viewContainer addSubview:sectionHeader];
        sectionHeader.delegate = self;
        [sectionHeader release];
    }
     */
    
    
    _departureView = [[RCDepartureAndArriveView alloc] initWithFrame:CGRectMake(0, 65-diffHeight, 320, 75) andType:RCDepartureAndArriveViewType_RoundTripDes];
    [self.viewContainer addSubview:_departureView];
    if (_type == TicketType_Air) {
        [_departureView setLeft:@"广州" withLeftID:@"CAN"];
        [_departureView setRight:@"北京首都" withRightID:@"PEK"];
    }else{
        [_departureView setLeft:@"广州" withLeftID:@"CAN"];
        [_departureView setRight:@"北京" withRightID:@"PEKNAY"];
    }
  
    _departureView.delegate = self;
    [_departureView release];
    
    
    if (_type == TicketType_Air) {
        _timeView = [[RCDepartureAndArriveView alloc] initWithFrame:CGRectMake(0, 140-diffHeight, 320, 75) andType:RCDepartureAndArriveViewType_SingleTripTime];
    }else{
        _timeView = [[RCDepartureAndArriveView alloc] initWithFrame:CGRectMake(0, 140-diffHeight, 320, 75) andType:RCDepartureAndArriveViewType_SingleTripTime];
    }
    
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
    
    NSInteger day = [components day];
    
    NSInteger month= [components month];
    
    NSInteger year= [components year];
    NSString *dateStr = [NSString stringWithFormat:@"%d-%d-%d",year,month,day];
    [_timeView setLeft:dateStr withLeftID:Nil];
    [_timeView setRight:dateStr withRightID:Nil];

    
    _timeView.delegate = self;
    [self.viewContainer addSubview:_timeView];
    [_timeView release];
    
    
    
    
    if (_type == TicketType_Air) {
        _seatTypeView = [[RCDepartureAndArriveView alloc] initWithFrame:CGRectMake(0, 215-diffHeight, 320, 75) andType:RCDepartureAndArriveViewType_SeatTypeView];
        [_seatTypeView setLeft:[planeSeatType objectAtIndex:0] withLeftID:Nil];
    }else{
        _seatTypeView = [[RCDepartureAndArriveView alloc] initWithFrame:CGRectMake(0, 215-diffHeight, 320, 75) andType:RCDepartureAndArriveViewType_TrainTypeView];
        [_seatTypeView setLeft:[trainType objectAtIndex:0] withLeftID:Nil];
        [_seatTypeView setRight:[allTrainSeatType objectAtIndex:0] withRightID:Nil];
    }
    _seatTypeView.delegate = self;
    [self.viewContainer addSubview:_seatTypeView];
    [_seatTypeView release];
    
    
    
    UIButton *searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(14, 290-diffHeight, 320-28, 40)];
    [searchBtn setTitle:@"查询" forState:UIControlStateNormal];
    [self.viewContainer addSubview:searchBtn];
    UIImage *loginIMG = [UIImage imageNamed:@"login_btn"];
    [searchBtn setBackgroundImage:loginIMG forState:UIControlStateNormal];
    //        [loginBtn setBackgroundColor:[UIColor blackColor]];
    [searchBtn addTarget:self action:@selector(searchPress:) forControlEvents:UIControlEventTouchUpInside];
    [searchBtn release];
    
    _trainPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, UIScreenHeight-44-20-150, 320, 150)];
    _trainPickerView.showsSelectionIndicator = YES;
    
    [self.viewContainer addSubview:_trainPickerView];
    [_trainPickerView release];
    _trainPickerView.delegate = self;
    _trainPickerView.hidden = YES;
    
    planeToolBar = [self createToolBar];
    [self.viewContainer addSubview:planeToolBar];
    [planeToolBar release];
    planeToolBar.hidden = YES;
    
    _planePickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, UIScreenHeight-44-20-150, 320, 150)];
    _planePickerView.showsSelectionIndicator = YES;
    [self.viewContainer addSubview:_planePickerView];
    _planePickerView.delegate = self;
    _planePickerView.hidden = YES;
    [_planePickerView release];
    
    trainToolBar = [self createToolBar];
    [self.viewContainer addSubview:trainToolBar];
    [trainToolBar release];
    trainToolBar.hidden = YES;
    
}


-(void)createTitleButtonView{
    _headerTitleButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 157, 36)];
    _headerTitleButton.backgroundColor = [UIColor clearColor];
    [_headerTitleButton addTarget:self action:@selector(headerTitleButtonClicked) forControlEvents:UIControlEventTouchUpInside];
#define kHeaderTitleImageFile          @"image_topList_headerView_button.png"
    
    [_headerTitleButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kHeaderTitleImageFile ofType:nil]] forState:UIControlStateNormal];
    
    _headerTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 120, 16)];
    _headerTitleLabel.backgroundColor = [UIColor clearColor];
    _headerTitleLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
    _headerTitleLabel.textColor = [UIColor whiteColor];
    _headerTitleLabel.textAlignment = NSTextAlignmentCenter;
    [_headerTitleButton addSubview:_headerTitleLabel];
    
    if (_type == TicketType_Air) {
        _headerTitleLabel.text =@"国内/国际机票";
        self.orderType = @"TicketType_Air";
    }else{
        _headerTitleLabel.text =@"火车票";
        self.orderType = @"TicketType_Train";
    }
    self.navigationItem.titleView = _headerTitleButton;
    
    
    
    RCTopListTypeDataModel *model = [[RCTopListTypeDataModel alloc] init];
    NSMutableArray *mutArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < 2; i ++) {
        RCTopListTypeCategoryItem *item = [[RCTopListTypeCategoryItem alloc] init];
        if (i == 0) {
            item.categoryID = @"TicketType_Air";
            item.categoryName = @"国内/国际机票";
        }else if (i == 1){
            item.categoryID = @"TicketType_Train";
            item.categoryName = @"火车票";
        }
        [mutArr addObject:item];
        [item release];
    }
    model.categoryListArray = mutArr;
    [mutArr release];
    
    _typeListView = [[RCToplistTypeView alloc]initWithFrame:CGRectMake(0, 0, 320, 80) andDataSource:model];
    _typeListView.delegate = self;
    _typeListView.hidden = YES;
    [self.view addSubview:_typeListView];
    
    _transparentButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 80, 320, UIScreenHeight-64-80)];
    
    _transparentButton.backgroundColor = [UIColor colorWithHex:0x77000000];
    [_transparentButton addTarget:self action:@selector(transparentButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    _transparentButton.hidden = YES;
    [self.view addSubview:_transparentButton];
    
    [model release];
    
}



-(void)headerTitleButtonClicked{
    
 
    if (!_typeListView) {
        return;
    }
    if (_typeListView.hidden) {
        _typeListView.hidden = NO;
        _transparentButton.hidden = NO;
        [self.viewContainer bringSubviewToFront:_typeListView];
        [self.viewContainer bringSubviewToFront:_transparentButton];
    }else{
        _typeListView.hidden = YES;
        _transparentButton.hidden = YES;
    }
}


- (void) selectToplistTypeItem:(RCTopListTypeCategoryItem *)item
{
    if ([item.categoryID isEqualToString:@"TicketType_Train"]) {
        _type = TicketType_Train;
    }else{
        _type = TicketType_Air;
    }
    if (_type == TicketType_Air) {
        _headerTitleLabel.text =@"国内/国际机票";
        self.orderType = @"TicketType_Air";
    }else{
        _headerTitleLabel.text =@"火车票";
        self.orderType = @"TicketType_Train";
    }
    

    
    [self setViewContainerSubviews];
    
    [self transparentButtonClicked];
    
}

-(void)transparentButtonClicked{
    _typeListView.hidden = YES;
    _transparentButton.hidden = YES;
    _trainPickerView.hidden = YES;
    _planePickerView.hidden = YES;
    planeToolBar.hidden = YES;
    trainToolBar.hidden = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//用户点击 单程 还是 双程
- (void) userDidClickAtIndex:(NSInteger)index
{
    if (index == 0) {
        [_timeView changeToMode:RCDepartureAndArriveViewType_SingleTripTime];
    }else{
        [_timeView changeToMode:RCDepartureAndArriveViewType_RoundTripTime];

    }
    
}


- (void) searchPress:(id) sender
{

    if (![[GloableEngineService sharedInstance]alertLoginViewIfUnlogin:self]) {
        return;
    }
    NSString *startTrainPort = [_departureView leftStr];
    NSString *endTrainPort = [_departureView rightStr];
    

    NSString *startTime = [_timeView leftStr];
    
    if (_type == TicketType_Air) {
        //飞机
        NSString *startPort3words = [_departureView leftValue];
        NSString *endPort3words = [_departureView rightValue];
        NSString *seatTypeStr =  [_seatTypeView leftStr];
        NSInteger seatTypeInt = 0;
        
        for (NSString *str in planeSeatType) {
            if ([str isEqualToString:seatTypeStr]) {
                break;
            }
            seatTypeInt ++;
        }
        
        RCAirFlyListVC *vc = [[RCAirFlyListVC alloc] init];
        vc.startPortName =startTrainPort; //bar显示
        vc.endPortName = endTrainPort; //bar显示

        vc.startTime = startTime;
        vc.endTrainPort = endPort3words; //网络查询 3words
        vc.startTrainPort = startPort3words;//网络查询 3words
        vc.seatTypeInt = seatTypeInt;
        
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }else{
      
        //火车
      
        NSString *trainTypeStr =  [_seatTypeView leftStr];
        NSString *seatTypeStr =  [_seatTypeView rightStr];
        NSInteger trainTypeInt = 0;
        NSInteger seatTypeInt = 0;
        
        for (NSString *str in trainType) {
            if ([str isEqualToString:trainTypeStr]) {
                break;
            }
            trainTypeInt ++;
        }
        
        for (NSString *str in allTrainSeatType) {
            if ([str isEqualToString:seatTypeStr]) {
                break;
            }
            seatTypeInt ++;
        }
        

        RCTrainListVC *vc = [[RCTrainListVC alloc] init];
        vc.startTrainPort = startTrainPort;
        vc.endTrainPort = endTrainPort;
        vc.startTime = startTime;
        vc.trainTypeInt = trainTypeInt;
        vc.seatTypeInt = seatTypeInt;
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }
    
}

- (void) rcDepartureAndArriveViewClickAtSide:(NSInteger)side withState:(RCDepartureAndArriveViewType)type
{
    _side = side;
    if (type == RCDepartureAndArriveViewType_RoundTripDes) {
        _rowNumberClick = 0;
        if (_type == TicketType_Train) {
            RCEditAllCityVC *vc = [[RCEditAllCityVC alloc] init];
            vc.reqType = CityListType_TrainPort;
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
            [vc release];
            return;
        }else if (_type == TicketType_Air){
            RCEditAllCityVC *vc = [[RCEditAllCityVC alloc] init];
            vc.reqType = CityListType_AirPort;
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
            [vc release];
            return;
        }
    }else if (type == RCDepartureAndArriveViewType_RoundTripTime){
        _rowNumberClick = 1;
    }else if (type == RCDepartureAndArriveViewType_SingleTripTime){
        _rowNumberClick = 1;
        CalendarVC *t = [[CalendarVC alloc] init];
        t.delegate = self;
        [self.navigationController pushViewController:t animated:YES];
        [t release];
        return;
        
    }else if (type == RCDepartureAndArriveViewType_SeatTypeView){
        _rowNumberClick = 2;
       
//        _transparentButton.hidden = NO;
        _trainPickerView.hidden = YES;
        trainToolBar.hidden = YES;
        _planePickerView.hidden = NO;
        planeToolBar.hidden = NO;
    }else if (type == RCDepartureAndArriveViewType_TrainTypeView){
        _rowNumberClick = 2;
        trainToolBar.hidden = NO;
        _trainPickerView.hidden = NO;
        _planePickerView.hidden = YES;
        planeToolBar.hidden = YES;

    }
}


//更换地点
- (void) changeCityTo:(NSString *)cityName withCityID:(NSString *)cityID
{
    if (_rowNumberClick == 0) {
        if (_side == 0) {
            [_departureView setLeft:cityName withLeftID:cityID];
        }else{
            [_departureView setRight:cityName withRightID:cityID];
        }
    }else if (_rowNumberClick == 1){
        if (_side == 0) {
            
        }else{
            
        }
    }else if (_rowNumberClick == 2){
        if (_side == 0) {
            
        }else{
            
        }
    }
}


#pragma mark PickView Delegate
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    if (_type == TicketType_Air) {
        return 1;
    }else{
        return 2;

    }
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{

    if (_type == TicketType_Air) {
        return 2;
    }else{
        if (component == 0) {
            return 3;
        }else{
            NSInteger currentSelectedLeft = [pickerView selectedRowInComponent:0];
            if (currentSelectedLeft == 0) {
                return [allTrainSeatType count];
            }else  if (currentSelectedLeft == 1) {
                return [gaotieTrainSeatType count];
            }else{
                return [putongTrainSeatType count];
            }
            
        }
    }
   
   

}


-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString *t = Nil;

    if (_type == TicketType_Air) {
        t = [planeSeatType safeObjectAtIndex:row];
    }else{
        if (component == 0) {
            t = [trainType safeObjectAtIndex:row];
        }else{
            
            NSInteger type = [pickerView selectedRowInComponent:0];
            if (type == 0) {
                t = [allTrainSeatType safeObjectAtIndex:row];
            }else  if (type == 1) {
                t = [gaotieTrainSeatType safeObjectAtIndex:row];
            }else{
                t = [putongTrainSeatType safeObjectAtIndex:row];
            }
            
        }
    }
    return t;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (_type == TicketType_Air) {
        
    }else{
        if (component == 0) {
            [pickerView selectRow:0 inComponent:1 animated:NO];
        }
        [pickerView reloadAllComponents];
    }

}


- (UIView *) createToolBar
{
    CGFloat yPoint = 0;
    if (_type == TicketType_Air) {
        yPoint = _planePickerView.frame.origin.y-40;
    }else{
        yPoint = _trainPickerView.frame.origin.y-40;
    }
    UIView *s = [[[UIView alloc] initWithFrame:CGRectMake(0, yPoint, 320, 40)]autorelease];
    [s setBackgroundColor:kNormalOrangeTextColor];
    
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 50, 40)];
    [leftBtn addTarget:self action:@selector(cancelBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [leftBtn setTitle:@"取消" forState:UIControlStateNormal];
    [leftBtn.titleLabel setFont:[UIFont fontWithName:kFontNameHeiti size:16]];
    [leftBtn setTitleColor:kNormalHeadTextColor forState:UIControlStateNormal];
    [leftBtn setBackgroundColor:[UIColor clearColor]];
    
    [s addSubview:leftBtn];
    [leftBtn release];
    
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, 220, 40)];
    [s addSubview:textLabel];
    [textLabel setBackgroundColor:[UIColor clearColor]];
    textLabel.textAlignment = NSTextAlignmentCenter;
    [textLabel release];
    if (_type == TicketType_Air) {
        textLabel.text = @"舱位选择";
    }else{
        textLabel.text = @"选择车次和座席类型";
    }
    
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(260, 0, 50, 40)];
    [s addSubview:rightBtn];
    [rightBtn addTarget:self action:@selector(confirmBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"确定" forState:UIControlStateNormal];
    [rightBtn.titleLabel setFont:[UIFont fontWithName:kFontNameHeiti size:16]];
    [rightBtn setTitleColor:kNormalHeadTextColor forState:UIControlStateNormal];
    [rightBtn setBackgroundColor:[UIColor clearColor]];
    [rightBtn release];
    return s;
    
}

- (void) cancelBtnPressed
{
    planeToolBar.hidden = YES;
    trainToolBar.hidden = YES;
    _planePickerView.hidden = YES;
    _trainPickerView.hidden = YES;
}


- (void) confirmBtnPressed
{
    planeToolBar.hidden = YES;
    trainToolBar.hidden = YES;
    _planePickerView.hidden = YES;
    _trainPickerView.hidden = YES;
    
    if (_type == TicketType_Train) {
        NSInteger left  =   [_trainPickerView selectedRowInComponent:0];
        NSInteger right  =   [_trainPickerView selectedRowInComponent:1];

        [_seatTypeView setLeft:[trainType objectAtIndex:left] withLeftID:Nil];
        if (left == 0) {
            [_seatTypeView setRight:[allTrainSeatType objectAtIndex:right] withRightID:nil];
        }else if (left == 1){
            [_seatTypeView setRight:[gaotieTrainSeatType objectAtIndex:right] withRightID:nil];
        }else{
            [_seatTypeView setRight:[putongTrainSeatType objectAtIndex:right] withRightID:nil];
        }
    }else{
        NSInteger left  =   [_planePickerView selectedRowInComponent:0];
//        NSInteger right =   [_planePickerView selectedRowInComponent:1];
        [_seatTypeView setLeft:[planeSeatType objectAtIndex:left] withLeftID:Nil];
        
    }
    
}

- (void) didSelectDate:(NSString *)date
{
    [_timeView setLeft:date withLeftID:Nil];

}

@end
